import { login, logout, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
import { constantRoutes, allAsyncRoutes, anyRoutes } from "@/router/index";
import router from "@/router/index";
import _ from "lodash";

// 根据当前路由信息，过滤得到对应的路由权限数组
function filtrateAllSyncRoutes(routes, userRoutes) {
  // 存储过滤后的路由
  const newRoutes = [];
  routes.forEach((item) => {
    if (userRoutes.includes(item.name)) {
      if (item.children && item.children > 0) {
        item.children = filtrateAllSyncRoutes(item.children, userRoutes);
      }
      newRoutes.push(item);
    }
  });
  return newRoutes;
}

const getDefaultState = () => {
  return {
    // 登录成功后的用户token
    token: getToken(),
    // 登录成功后的用户名
    name: "",
    // 登录成功后的用户头像
    avatar: "",
    // 登录成功后的用户菜单，路由列表
    routes: [],
    // 登录成功后的用户按钮（页面功能）列表
    buttons: [],
    // 登录成功后的用户角色列表
    roles: [],
    // 不同角色的用户要显示的管理菜单
    menuRoutes: [],
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROUTES: (state, routes) => {
    state.routes = routes;
  },
  SET_BUTTONS: (state, buttons) => {
    state.buttons = buttons;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_USERS: (state, data) => {
    router.addRoutes([...data, ...anyRoutes]);
    state.menuRoutes = [...constantRoutes, ...data];
  },
};

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then((response) => {
          const { data } = response;
          commit("SET_TOKEN", data.token);
          // 用户登录成功后的token保存到localStorage中（持久化）
          setToken(data.token);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then((response) => {
          const { data } = response;

          if (!data) {
            return reject("Verification failed, please Login again.");
          }

          const { name, avatar, routes, buttons, roles } = data;

          commit("SET_NAME", name);
          commit("SET_AVATAR", avatar);
          commit("SET_ROUTES", routes);
          commit("SET_BUTTONS", buttons);
          commit("SET_ROLES", roles);

          const userRoutes = filtrateAllSyncRoutes(
            _.cloneDeep(allAsyncRoutes),
            routes
          );
          console.log("userRoutes", userRoutes);

          // 把路由注册到路由表中

          commit("SET_USERS", userRoutes);
          // commit("SET_USERS", {
          //   token: getToken(),
          //   name: state.name,
          //   avatar: state.avatar,
          //   routes: state.routes,
          //   buttons: state.buttons,
          //   roles: state.roles,
          //   menuRoutes: [...constantRoutes, ...userRoutes],
          // });

          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken(); // must remove  token  first
          resetRouter();
          commit("RESET_STATE");
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
